//
//  FilesystemView.mm
//  MantuPlay
//
//  Created by Markus Sintonen on 21.3.2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "FilesystemView.h"

@implementation File

@synthesize name, path, isDirectory;
@end

#define SEARCHBAR_HEIGHT 44

@implementation FilesystemView

@synthesize tableView;

- (id)initWithDirectory:(NSString*)dir {
    if (self = [super init]) {
		currentDirectory = [[NSString alloc] initWithString:dir];
		currentDirectoryContents = [[NSMutableArray alloc] init];
		
		self.title = @"File System";
		
		//CGRect origFrame = self.tableView.frame;
		//self.tableView.frame = CGRectMake(origFrame.origin.x, origFrame.origin.y + 100.0, origFrame.size.width, origFrame.size.height);
	}
    return self;
}

- (void)loadView {
	CGRect applicationFrame = [[UIScreen mainScreen] bounds];
	
	CGRect fileTableViewRect = applicationFrame;
	fileTableViewRect.origin.y = applicationFrame.origin.y + SEARCHBAR_HEIGHT;
	
	fileTableView = [[UITableView alloc] initWithFrame:fileTableViewRect style:UITableViewStylePlain];
	fileTableView.delegate = self;
	fileTableView.dataSource = self;
	
	fileTableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
	fileTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	
	CGRect searchBarRect = applicationFrame;
	searchBarRect.size.height = SEARCHBAR_HEIGHT;
	
	UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:searchBarRect];

	UIView *viewHolder = [[UIView alloc] initWithFrame:applicationFrame];
	[viewHolder addSubview:fileTableView];
	[viewHolder addSubview:searchBar];
	
	self.view = viewHolder;
	
	[viewHolder release];
	
	/*UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
															target:self action:@selector(searchClicked:)];
	self.navigationItem.rightBarButtonItem = rightItem;
	[rightItem release];*/
	
	[self getCurrentDirectoryContents];
	
	[self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

-(void)getCurrentDirectoryContents {
	currentDirectoryContents = [[NSMutableArray alloc] init];
	
	NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:currentDirectory];
	NSString *fileName;
	
	while (fileName = [dirEnum nextObject]) {
		File *file = [[File alloc] init];
		
		file.name = fileName;
		file.path = [currentDirectory stringByAppendingFormat:@"/%@", fileName];
		
		if([[[dirEnum fileAttributes] valueForKey:NSFileType] isEqualToString:NSFileTypeDirectory]) {
			file.isDirectory = [NSNumber numberWithBool:YES];
			[dirEnum skipDescendents];
		}
		else {
			file.isDirectory = [NSNumber numberWithBool:NO];
		}
		[currentDirectoryContents addObject:file];
		[file release];
	}
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [currentDirectoryContents count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"FilesystemCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0,0,0,0) reuseIdentifier:CellIdentifier] autorelease];
    }
	
	File *file = (File*)[currentDirectoryContents objectAtIndex:indexPath.row];
    
	cell.text = file.name;
	
	if([file.isDirectory boolValue]) {
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	File *selectedFile = (File*)[currentDirectoryContents objectAtIndex:indexPath.row];
	
	if([selectedFile.isDirectory boolValue]) {
		FilesystemView *anotherViewController = [[FilesystemView alloc] initWithDirectory:selectedFile.path];
		[self.navigationController pushViewController:anotherViewController animated:YES];
		[anotherViewController release];
	}
	else {
		if([[selectedFile.name pathExtension] isEqualToString:@"mp3"]) {
			NSError *err;
			AVController *avController = [[AVController alloc] init];
			AVItem *item = [[AVItem alloc] initWithPath:selectedFile.path error:&err];
			
			if(err == nil) {
				BOOL ok;
				AVQueue *avq = [[AVQueue alloc] init];
				[avController setQueue:avq];
				[avq appendItem:item error:&err];
				if(err == nil) ok = [avController play:nil];
			}
		}
	}
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

- (void)dealloc {
    [super dealloc];
}


@end

